<?php

class User_RegisterController extends User_Library_Controller_Action
{

    public function init()
    {
        parent::init();
        $this->_model = new Model_User();
        $this->_form = new User_Form_User();
    }

    /**
     * @todo Register account
     * @return void
     */
    public function indexAction()
    {
        if ($this->getRequest()->isPost()) {
            $tableName = $this->_model->getMapper()->getDbTable()->getTableName();

            $email = $this->_form->getElement('email');
            $email->addValidator('Db_NoRecordExists', false, array('table' => $tableName, 'field' => 'email'));
            $email->getValidator('Db_NoRecordExists')->setMessage($this->view->translate('EMAIL_REGISTERED'));

            $phone = $this->_form->getElement('phone');
            $phone->addValidator('Db_NoRecordExists', false, array('table' => $tableName, 'field' => 'phone'));
            $phone->getValidator('Db_NoRecordExists')->setMessage($this->view->translate('PHONE_REGISTERED'));

            if ($this->_form->isValid($this->getRequest()->getPost())) {
                /*
                // Processing for upload file
                if ($this->_form->file->receive()) {
                    $image = $this->_form->file->getFileName('', false);
                    if(empty($image)) {
                        if($this->getRequest()->getParam('gender') == 0) {
                            $this->getRequest()->setParam('image', 'no_image_female.png');
                        }
                        else {
                            $this->getRequest()->setParam('image', 'no_image_male.png');
                        }
                    }
                    else {
                        $this->getRequest()->setParam('image', $image);
                    }
                     
                }*/
                $this->getRequest()->setParam('published', 1);
                if($this->getRequest()->getParam('gender') == 0) {
                    $this->getRequest()->setParam('image', 'no_image_female.png');
                }
                else {
                    $this->getRequest()->setParam('image', 'no_image_male.png');
                }

                $email = $this->getRequest()->getParam('email');
                $activeCode = $this->generateCode('active');
                $this->getRequest()->setParam('active_code', $activeCode);
                $result = $this->save();
                $this->_helper->flashMessenger->addMessage($result);
                if ($result['result'] == 'success') {
                    try {
                        $this->sendMailConfirm($email, $fullname, $activeCode);
                    }
                    catch (Zend_Exception $e) {
                        $logger = Zend_Registry::get('logger');
                        $params = $this->getRequest()->getParams();
                        $message = $e->getMessage() . "\n" . $e->getTraceAsString() . "\n Param: \n" . var_export($params, true) . "\n";
                        $logger->log($message, Zend_Log::DEBUG);
                    }
                    
                    $urlOptions = array('module'=>'user', 'controller'=>'register', 'action'=>'result', 'value'=>'successful');
                    $this->_helper->redirector->gotoRoute($urlOptions);
                }
            }
        }

        //$this->view->headLink()->appendStylesheet($this->view->themePath . '/css/datepicker.css');
        //$this->view->headScript()->appendFile($this->view->themePath . '/js/bootstrap-datepicker.js', 'text/javascript');
        $this->view->form = $this->_form;
    }

    /**
     * @todo Active account
     * @return void
     */
    public function activeAction()
    {
        $email = $this->getRequest()->getParam('email');
        $code = $this->getRequest()->getParam('code');
        if($code && $email) {
            try {
                $verifyCode = $this->generateCode('verify');
                $this->sendSMSVerify(base64_decode($email), $verifyCode);
            }
            catch (Zend_Exception $e) {
                $logger = Zend_Registry::get('logger');
                $params = $this->getRequest()->getParams();
                $message = $e->getMessage() . "\n" . $e->getTraceAsString() . "\n Param: \n" . var_export($params, true) . "\n";
                $logger->log($message, Zend_Log::DEBUG);
            }
            
            $result = $this->_model->activeAccount(base64_decode($email), $code);
            if($result > 0) {
                $this->_forward('result', 'register', 'user', array('value' => 'verify', 'email' => $email));
            }
            else {
                $this->_forward('result', 'register', 'user', array('value' => 'failed', 'email' => $email));
            }
        }
        else {
            $this->_redirect('');
        }
    }

    /**
     * @todo Active account
     * @return void
     */
    public function resultAction()
    {
        $result = $this->getRequest()->getParam('value');
        $email = $this->getRequest()->getParam('email');
        if($result == 'successful') {
            $this->_helper->viewRenderer('successful');
        }
        else if($result == 'verify') {
            $this->_redirect('/user/register/verify/email/'.$email);
        }
        else {
            $this->_helper->viewRenderer('failed');
        }
    }

    /**
     * @todo Verify account
     * @return void
     */
    public function verifyAction()
    {
        $this->_form = new User_Form_Verify();
        $email = $this->getRequest()->getParam('email');
        $email = base64_decode($email);
        if ($this->getRequest()->isPost()) {
            if ($this->_form->isValid($this->getRequest()->getPost())) {
                $code = $this->getRequest()->getParam('verifycode');
                $result = $this->_model->verifyAccount($email, $code);
                if($result > 0) {
                    $this->_forward('result', 'register', 'user', array('value' => 'successful'));
                }
                else {
                    $this->_forward('result', 'register', 'user', array('value' => 'failed'));
                }
            }
        }
        $this->_form->getElement('email')->setValue($email);
        $this->view->form = $this->_form;
    }

    private function sendMailConfirm($email, $fullname, $code)
    {
        try {
            $urlOptions = array(
                'module' => 'user',
                'controller' => 'register',
                'action' => 'active',
                'email' => base64_encode($email),
                'code' => $code);
            $linkActive = $this->view->url($urlOptions, 'default', false);

            $view = new Zend_View();
            $view->setScriptPath(APP_PATH . DS . 'layouts');
            $view->fullname = $fullname;
            $view->activeURL = $linkActive;

            $mail = new Zend_Mail('utf-8');
            $mail->addTo($email, $fullname);
            $mail->setSubject($this->view->translate('REGISTER_ACTIVE_SUBJECT'));
            $body = $view->render('emailtemplate/confirm-register.phtml');
            $mail->setBodyHtml($body);
            $mail->send();
        }
        catch (Zend_Exception $e) {
            $logger = Zend_Registry::get('logger');
            $params = $this->getRequest()->getParams();
            $message = $e->getMessage() . "\n" . $e->getTraceAsString() . "\n Param: \n" . var_export($params, true) . "\n";
            $logger->log($message, Zend_Log::DEBUG);
        }
    }

    private function sendSMSVerify($email, $code)
    {
        $result = $this->_model->search('email', $email);
        if(count($result)) {
            $object = array_shift(array_values($result));
            $object->setVerifyCode($code);
            if($object->save()) {
                $config = Zend_Registry::get('configuration');
                $fiboClientNo = $config->fibo_client_no;
                $fiboClientPass = $config->fibo_client_pass;
                $restClient = new Zend_Rest_Client($config->fibo_uri);
                $params = array(
                    'clientNo' => $fiboClientNo,
                    'clientPass' => $fiboClientPass,
                    'phoneNumber' => $object->getPhone(),
                    'smsMessage' => 'Bizbid project. Your verify code is: '. $code,
                    'smsGUID' => $code,
                    'serviceType' => 1); // test mode
                
                
                $response = $restClient->restGet('/Service.asmx/SendSMS', $params);
                $body = $response->getBody();
                $body = html_entity_decode($body);
                $xml = new Zend_Config_Xml($body);
                $arr = $xml->toArray();
                
                /*array(1) {
                ["SMS"] => array(3) {
                ["Code"] => string(3) "200"
                ["Message"] => string(10) "Sending..."
                ["Time"] => string(0) ""
                }
                }*/
            }
        }
        else {
            $logger = Zend_Registry::get('logger');
            $logger->log('Can not send SMS because the email not found', Zend_Log::DEBUG);
        }
    }

    private function save()
    {
        $msg = array();
        if (is_object($this->_model)) {
            try {
                $attributes = $this->_model->buildAttributes($this->getRequest()->getParams());
                $this->_model->setOptions($attributes);
                $result = $this->_model->save();
                if ($result) {
                    // Create Role
                    $aclUser = new Model_AclUser();
                    $aclUser->setOptions(array('role_id' => 4, 'user_id' => $result));
                    $result = $aclUser->save();
                    if($result) {
                        $msg = array(
                            'result' => 'success',
                            'message' => $this->view->translate('MSG_SUCCESS_SAVE')
                        );
                    }
                    else {
                        $msg = array(
                            'result' => 'success',
                            'message' => $this->view->translate('MSG_FAILED_ACL_SAVE')
                        );
                    }
                } else {
                    $msg = array(
                        'result' => 'failed',
                        'message' => $this->view->translate('MSG_FAILED_SAVE')
                    );
                }
            } catch (Zend_Exception $e) {
                $msg = array(
                    'result' => 'failed',
                    'message' => $e->getMessage()
                );
            }
        } else {
            $msg = array(
                'result' => 'error',
                'message' => $this->view->translate('MSG_ERROR_MODEL_NOT_INITIAL')
            );
        }

        return $msg;
    }
}